//
//  WHAppDelegate+WHAppService.m
//  SquirrelSeller
//
//  Created by 邓伟浩 on 2018/12/29.
//  Copyright © 2018 邓伟浩. All rights reserved.
//

#import "WHAppDelegate+WHAppService.h"
#import "WHRootNavigationController.h"
#import "WHLoginController.h"

@implementation WHAppDelegate (WHAppService)

- (void)setUpAppService {
    [userManager defaultSetting];
    [self registNotification];
    [self setUpRootViewController];
}

- (void)registNotification {
    [kNotificationCenter addObserver:self
                            selector:@selector(loginStateChange:)
                                name:KNotificationLoginStateChange
                              object:nil];
}

- (void)setUpRootViewController {
    if([userManager loadUserInfo]) {
        [self showMainModules];
    } else {
        [self showLoginModules];
    }
}

#pragma mark ————— 登录状态处理 —————
- (void)loginStateChange:(NSNotification *)notification {
    BOOL loginSuccess = [notification.object boolValue];
    
    if (loginSuccess) { // 登陆成功加载主窗口控制器
        
        //为避免自动登录成功刷新tabbar
        if (!self.mainTabBar || ![self.window.rootViewController isKindOfClass:[CYLTabBarController class]]) {
            
            [self showMainModules];
            
            CATransition *anima = [CATransition animation];
            anima.type = @"reveal";//设置动画的类型
            anima.subtype = kCATransitionFromTop; //设置动画的方向
            anima.duration = 0.3f;
            
            [kAppWindow.layer addAnimation:anima forKey:@"revealAnimation"];
            [WHView showHudMsg:@"登录成功"];
        }
    } else { //登陆失败加载登陆页面控制器
        
        [self showLoginModules];
        
        CATransition *anima = [CATransition animation];
        anima.type = @"reveal";//设置动画的类型
        anima.subtype = kCATransitionFromBottom; //设置动画的方向
        anima.duration = 0.3f;
        
        [kAppWindow.layer addAnimation:anima forKey:@"revealAnimation"];
        [WHView showHudMsg:@"退出登录"];
    }
}

- (void)showMainModules {
    WHTabBarControllerConfig *tabBarControllerConfig = [[WHTabBarControllerConfig alloc] init];
    CYLTabBarController *tabBarController = tabBarControllerConfig.tabBarController;
    self.mainTabBar = tabBarController;
    self.window.rootViewController = tabBarController;
}

- (void)showLoginModules {
    WHLoginController *login = [[WHLoginController alloc] init];
    WHRootNavigationController *rootNavi = [[WHRootNavigationController alloc] initWithRootViewController:login];
    self.mainTabBar = nil;
    self.window.rootViewController = rootNavi;
}

@end
